package com.budwk.app.miniapp.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.budwk.app.miniapp.services.WxUserAuthService;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.budwk.app.miniapp.models.WxUser;
import com.budwk.app.miniapp.services.WxUserService;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import org.nutz.lang.Strings;
import com.budwk.starter.common.openapi.annotation.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

@IocBean
@At("/platform/miniapp/user")
@ApiDefinition(tag = "微信小程序-用户管理")
@Slf4j
public class WxuserController {
    @Inject
    private WxUserService wxUserService;
    @Inject
    private WxUserAuthService wxUserAuthService;

    @At("/list")
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询WxUser")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = WxUser.class
    )
    @ApiResponses(
            implementation = WxUser.class
    )
    @SaCheckLogin
    public Result<?> list(@Param("..") WxUser bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        }
        if (bean.getCreatedBy() != null && Strings.isNotBlank(bean.getCreatedBy().toString())) {
            cnd.and("create_id", "=", bean.getCreatedBy());
        }
        if (bean.getCreatedAt() != null && Strings.isNotBlank(bean.getCreatedAt().toString())) {
            cnd.and("create_time", "=", bean.getCreatedAt());
        }
        if (bean.getUpdatedBy() != null && Strings.isNotBlank(bean.getUpdatedBy().toString())) {
            cnd.and("update_id", "=", bean.getUpdatedBy());
        }
        if (bean.getUpdatedAt() != null && Strings.isNotBlank(bean.getUpdatedAt().toString())) {
            cnd.and("update_time", "=", bean.getUpdatedAt());
        }
        if (bean.getRemark() != null && Strings.isNotBlank(bean.getRemark().toString())) {
            cnd.and("remark", "=", bean.getRemark());
        }
        if (bean.getAppType() != null && Strings.isNotBlank(bean.getAppType().toString())) {
            cnd.and("app_type", "=", bean.getAppType());
        }
        if (bean.getSubscribe() != null && Strings.isNotBlank(bean.getSubscribe().toString())) {
            cnd.and("subscribe", "=", bean.getSubscribe());
        }
        if (bean.getSubscribeScene() != null && Strings.isNotBlank(bean.getSubscribeScene().toString())) {
            cnd.and("subscribe_scene", "=", bean.getSubscribeScene());
        }
        if (bean.getSubscribeTime() != null && Strings.isNotBlank(bean.getSubscribeTime().toString())) {
            cnd.and("subscribe_time", "=", bean.getSubscribeTime());
        }
        if (bean.getSubscribeNum() != null && Strings.isNotBlank(bean.getSubscribeNum().toString())) {
            cnd.and("subscribe_num", "=", bean.getSubscribeNum());
        }
        if (bean.getCancelSubscribeTime() != null && Strings.isNotBlank(bean.getCancelSubscribeTime().toString())) {
            cnd.and("cancel_subscribe_time", "=", bean.getCancelSubscribeTime());
        }
        if (bean.getOpenId() != null && Strings.isNotBlank(bean.getOpenId().toString())) {
            cnd.and("open_id", "=", bean.getOpenId());
        }
        if (bean.getNickName() != null && Strings.isNotBlank(bean.getNickName().toString())) {
            cnd.and("nickName", "=", bean.getNickName());
        }
        if (bean.getSex() != null && Strings.isNotBlank(bean.getSex().toString())) {
            cnd.and("sex", "=", bean.getSex());
        }
        if (bean.getCity() != null && Strings.isNotBlank(bean.getCity().toString())) {
            cnd.and("city", "=", bean.getCity());
        }
        if (bean.getCountry() != null && Strings.isNotBlank(bean.getCountry().toString())) {
            cnd.and("country", "=", bean.getCountry());
        }
        if (bean.getProvince() != null && Strings.isNotBlank(bean.getProvince().toString())) {
            cnd.and("province", "=", bean.getProvince());
        }
        if (bean.getPhone() != null && Strings.isNotBlank(bean.getPhone().toString())) {
            cnd.and("phone", "=", bean.getPhone());
        }
        if (bean.getLanguage() != null && Strings.isNotBlank(bean.getLanguage().toString())) {
            cnd.and("language", "=", bean.getLanguage());
        }
        if (bean.getUnionId() != null && Strings.isNotBlank(bean.getUnionId().toString())) {
            cnd.and("unionId", "=", bean.getUnionId());
        }
        if (bean.getGroupId() != null && Strings.isNotBlank(bean.getGroupId().toString())) {
            cnd.and("groupId", "=", bean.getGroupId());
        }
        if (bean.getTagidList() != null && Strings.isNotBlank(bean.getTagidList().toString())) {
            cnd.and("tagidList", "=", bean.getTagidList());
        }
        if (bean.getQrSceneStr() != null && Strings.isNotBlank(bean.getQrSceneStr().toString())) {
            cnd.and("qrSceneStr", "=", bean.getQrSceneStr());
        }
        if (bean.getLatitude() != null && Strings.isNotBlank(bean.getLatitude().toString())) {
            cnd.and("latitude", "=", bean.getLatitude());
        }
        if (bean.getLongitude() != null && Strings.isNotBlank(bean.getLongitude().toString())) {
            cnd.and("longitude", "=", bean.getLongitude());
        }
        if (bean.getPrecision() != null && Strings.isNotBlank(bean.getPrecision().toString())) {
            cnd.and("precision", "=", bean.getPrecision());
        }
        if (bean.getSessionKey() != null && Strings.isNotBlank(bean.getSessionKey().toString())) {
            cnd.and("session_key", "=", bean.getSessionKey());
        }
        if (bean.getPassword() != null && Strings.isNotBlank(bean.getPassword().toString())) {
            cnd.and("password", "=", bean.getPassword());
        }
        if (bean.getPoints() != null && Strings.isNotBlank(bean.getPoints().toString())) {
            cnd.and("points", "=", bean.getPoints());
        }
        if (bean.getReceiveEvent() != null && Strings.isNotBlank(bean.getReceiveEvent().toString())) {
            cnd.and("receive_event", "=", bean.getReceiveEvent());
        }
        return Result.data(wxUserService.listPage(pageNo, pageSize, cnd));
    }

    @At("/add")
    @Ok("json")
    @POST
    @ApiOperation(name = "新增WxUser")
    @ApiFormParams(
            implementation = WxUser.class
    )
    @ApiResponses
    @SLog(tag = "新增WxUser", value = "${args[0].id}")
    @SaCheckLogin
    public Result<?> create(@Param("..") WxUser wxUser, HttpServletRequest req) {
        wxUser.setCreatedBy(SecurityUtil.getUserId());
        wxUserService.insert(wxUser);
        return Result.success();
    }

    @At("/update")
    @Ok("json")
    @PUT
    @ApiOperation(name = "修改用户信息")
    @ApiFormParams(
            implementation = WxUser.class
    )
    @ApiResponses
    @SaCheckLogin
    public Result<?> update(@Param("..") WxUser wxUser, HttpServletRequest req) {
        if(StrUtil.isNotBlank(wxUser.getCardId())&&!IdcardUtil.isValidCard(wxUser.getCardId())){
            return Result.success("身份证号填写有误");
        }
        WxUser cardV= wxUserService.fetch(Cnd.where(WxUser::getCardId,"=",wxUser.getCardId()));
        if(ObjectUtil.isNotEmpty(cardV)&&!wxUser.getOpenId().equals(cardV.getOpenId())){
            return Result.success("身份证已存在！");
        }
       // wxUser.setUpdatedBy(StrUtil.subSuf(SecurityUtil.getUserId(),9));
        wxUser.setUpdatedBy(SecurityUtil.getUserId());
        wxUserService.updateIgnoreNull(wxUser);

        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取用户信息")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SaCheckLogin
    public Result<?> getData(@Param("id") String id, HttpServletRequest req) {
        WxUser wxUser = wxUserService.fetch(id);
        if (wxUser == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        return Result.data(wxUser);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除用户信息")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "删除用户信息", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> delete(@Param("id") String id, HttpServletRequest req) {
        WxUser wxUser = wxUserService.fetch(id);
        if (wxUser == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        wxUserService.delete(id);
        req.setAttribute("_slog_msg", wxUser.getId());
        return Result.success();
    }
}
